package com.ramblingcoder.bc2.server.tool.update.commands;

import java.util.Vector;

public class Response {
	private static int index = 0;
	
	public static final Parcel[] unpackParcel(byte[] input, int length){
		index = 0;
		
		byte[] inputSlim = new byte[length];
		
		System.arraycopy(input, 0, inputSlim, 0, length);

		Vector<Parcel> responses = new Vector<Parcel>(1);
		
		while (length != index){
			int id, numberOfWords;
			
			System.out.println(input.length);
			id = byteArrayToInt(new byte[]{input[index+0], input[index+1], input[index+2], (byte) (input[index+3] & 10111111 & 01111111)});
			
			numberOfWords = byteArrayToInt(new byte[]{input[index+8], input[index+9], input[index+10],input[index+11]});
			
			Parcel parcel = new Parcel(id, grabWords(input, numberOfWords));
			
			if (parcel.getWords().length == 0)
				break;
			
			responses.add(parcel);
		}
		
		Parcel[] array = new Parcel[responses.size()];
		responses.toArray(array);
		
		return array;
	}
	
	private static String[] grabWords(byte[] input, int numberOfWords) {
		String[] words = new String[numberOfWords];
		
		int numberIndex = index + 12; //13th byte
		for (int i = 0; i < numberOfWords; i++){
			int wordLength = byteArrayToInt(new byte[]{input[numberIndex + 0],input[numberIndex + 1],input[numberIndex + 2],input[numberIndex + 3]});
			
			words[i] = "";
			int wordIndex = numberIndex + 4;
			for (int a = 0; a < wordLength; a++)
				words[i] += (char)input[wordIndex + a];
			
			numberIndex = numberIndex + 4 + wordLength + 1; //+1 for the terminating byte
			index = numberIndex;
		}
		
		return words;
	}

	private static final int byteArrayToInt(byte[] b) {
		byte[] reversed = {b[3],b[2],b[1],b[0]};
		
		return 
			(reversed[0] << 24) + 
			((reversed[1] & 0xFF) << 16) + 
			((reversed[2] & 0xFF) << 8) + 
			(reversed[3] & 0xFF);
	}
}
